package correct.day6;

class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

public class Test2 {
    // 逆序链表
    public ListNode reverse(ListNode head)
    {
        ListNode newHead = new ListNode(0);
        ListNode cur = head;
        while(cur != null)
        {
            ListNode next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;
            cur = next;
        }
        return newHead.next;
    }

    public ListNode addInList (ListNode head1, ListNode head2)
    {
        // 1. 逆序
        head1 = reverse(head1);
        head2 = reverse(head2);
        // 2. ⾼精度加法
        ListNode cur1 = head1, cur2 = head2;
        int t = 0;
        ListNode ret = new ListNode(0), prev = ret;
        while(cur1 != null || cur2 != null || t != 0)
        {
            if(cur1 != null)
            {
                t += cur1.val;
                cur1 = cur1.next;
            }
            if(cur2 != null) {
                t += cur2.val;
                cur2 = cur2.next;
            }
            prev = prev.next = new ListNode(t % 10);
            t /= 10;
        }
        return reverse(ret.next);
    }
}
